<template>
  <div class="mining tabbar-iOS-height hideScrollBar" ref="scrollEl">
    <!-- 导航 -->
    <NavBar
      :isShowLeft="false"
      isFixed
      title="BDC Mining"
      :isTransparent="pageData.whiteTheme"
      :whiteTheme="pageData.whiteTheme"
      :navScorllOffset="60"
      navScorllColor="#FFF"
      :scrollEl="scrollEl"
      @getNavBarHeight="(h) => (pageData.navBarHeight = h)"
      @thresholdChange="(val) => (pageData.whiteTheme = !val)"
    />
    <!-- 背景 -->
    <div class="content">
      <!-- 背景色 -->
      <div class="content-color"></div>
      <!-- 下拉刷新 -->
      <ClientOnly>
        <van-pull-refresh
          class="pull-refresh"
          v-model="pageData.loading"
          :pulling-text="t('mvp.other.text9')"
          :loosing-text="t('mvp.other.text10')"
          loading-text=" "
          @refresh="onRefresh"
          @change="refreshChange"
        >
          <!-- 新人福利 -->
          <div
            v-if="inviterInfo"
            class="xrfl items-center"
            @click="isTaskPopupChange(true)"
          >
            <img
              class="xrfl-img"
              src="/image/inviteFriends/mining-zstc-icon.svg"
            />
            <div classs="xrfl-text">{{ $t("inviteFriends.xrfl") }}</div>
          </div>
          <!-- 挖矿 -->
          <div class="header">
            <img
              class="content-bg"
              :style="{
                top: `-${
                  pageData.navBarHeight > 44
                    ? pageData.navBarHeight - 44 + 100
                    : 30 + 102
                }px`,
              }"
              src="/image/mining/mining-bg.png"
            />
            <!-- 挖矿资产 -->
            <div class="items-center header-top" @click="jumpPage('assets')">
              <div class="header-top-bdc items-center">
                <!-- bdc收钱动画-锚点 -->
                <img
                  ref="bdcRef"
                  class="header-top-bdc-icon"
                  src="/image/mining/total-bdc.svg"
                />

                <div class="header-top-bdc-text">
                  {{ t("mvp.mining.text3") }}
                </div>
                <CountTo
                  class="header-top-bdc-value"
                  :startVal="pageData.mineInfo.cumulativeAcquireAmount"
                  :endVal="pageData.cumulativeAcquireAmount"
                  :duration="1500"
                  :decimals="2"
                ></CountTo>
                <img
                  class="header-top-bdc-jt"
                  src="/image/jt-blue-right-icon.svg"
                />
              </div>

              <img
                class="header-top-bg-left"
                src="/image/mining/total-right-icon.svg"
              />
              <img
                class="header-top-bg-right"
                src="/image/mining/total-right-icon1.svg"
              />
            </div>
            <!-- 宝箱 -->
            <div class="boxview" ref="boxview">
              <!-- 收钱动画 -->
              <template
                v-if="pageData.boxList.length > 0 && pageData.loadingAll"
              >
                <MiningBox
                  class="boxview-item items-center"
                  v-for="item in pageData.boxList"
                  :key="item.sort"
                  :style="{ left: `${item.x}`, top: `${item.y}px` }"
                  :item="item"
                  :bdcRect="bdcRect"
                  :isPaused="pageData.paused"
                  :manual="item.manual"
                  @openBox="openBoxCall(item)"
                />
              </template>
              <!-- 邀请好友抽奖 -->

              <div
                v-else-if="
                  pageData.boxList.length == 0 &&
                  pageData.loadingAll &&
                  lotteryV3Store.$state.isShowV3InviteLottery
                "
                class="inviteFriends items-center"
                @click="jumpPage('inviteFriendsMonery')"
              >
                <img
                  class="inviteFriends-img"
                  src="/image/inviteFriends/invite-friends-box.png"
                />
                <div class="inviteFriends-text">
                  {{ `${$t("lotteryMoney.yqhylcjDesc")}，` }} BDC
                </div>
              </div>
            </div>
            <!-- 星星 -->
            <img
              v-if="isShowXing"
              class="boxview-xing1 boxview-xingxing"
              :class="{ 'boxview-paused': pageData.paused }"
              src="/image/mvp/mvp/xingxing.svg"
            />
            <img
              v-if="isShowXing"
              class="boxview-xing2 boxview-xingxing"
              :class="{ 'boxview-paused': pageData.paused }"
              src="/image/mvp/mvp/xingxing.svg"
            />
            <img
              v-if="isShowXing"
              class="boxview-xing3 boxview-xingxing"
              :class="{ 'boxview-paused': pageData.paused }"
              src="/image/mvp/mvp/xingxing.svg"
            />
            <!-- 一键开箱 -->
            <div class="openall items-center">
              <div
                v-show="isShowOpenAllBtn"
                class="openall-bg"
                @click="bdcCollectAll"
              >
                <div class="openall-text">{{ t("mvp.mining.openAll") }}</div>
              </div>
            </div>
            <!-- 待领取 -->
            <div
              class="unclaimed items-center"
              @click="jumpPage('taskCenter', true)"
            >
              <div class="unclaimed-text">
                {{ $t("activity.mtjdllqjl") }}
              </div>
              <img class="unclaimed-icon" src="/image/mining/dlq-icon.svg" />
            </div>
            <!-- 动物 -->
            <div class="user">
              <img class="user-logo" :src="userLevel" />
            </div>
            <!-- 跑马灯 -->
            <Broadcast
              v-if="pageData.broadcasts.length > 1"
              class="broadcastview"
              :list="pageData.broadcasts"
              :speed="60"
            >
              <template #cell="data">
                <MiningCell
                  v-for="(source, index) in data.list"
                  :key="`${data.prefix}-${source.id || index}`"
                  :item="source"
                ></MiningCell>
              </template>
            </Broadcast>
          </div>
          <!-- 内容蒙层 -->
          <div class="mantle mantle-filter">
            <!-- 挖矿菜单 -->
            <div class="operate items-center">
              <div
                v-for="(item, index) in menus"
                class="operate-item items-center"
                @click="jumpPage(item.path, index < 2)"
              >
                <img
                  v-if="index == 0"
                  class="operate-item-icon"
                  src="/image/mining/dh-icon.svg"
                />
                <img
                  v-else-if="index == 1"
                  class="operate-item-icon"
                  src="/image/mining/jl-icon.svg"
                />
                <img
                  v-else-if="index == 2"
                  class="operate-item-icon"
                  src="/image/mining/bd-icon.svg"
                />
                <img
                  v-else-if="index == 3"
                  class="operate-item-icon"
                  src="/image/mining/desc-icon.svg"
                />
                {{ item.title }}
              </div>
            </div>
            <!-- 挖矿达人 -->
            <div class="miner">
              <!-- 标题 -->
              <div class="miner-top items-center">
                <div class="miner-top-title">{{ t("mvp.mining.text7") }}</div>
                <!-- 累计人数 -->
                <div class="miner-top-num">
                  {{ toThousands(pageData.miningNums) }}
                  <span class="miner-top-num-text">{{
                    $t("mvp.mining.text12")
                  }}</span>
                </div>
              </div>
              <div class="miner-list items-center">
                <template v-for="item in pageData.userList" :key="item.id">
                  <div
                    v-if="item === 'occupy'"
                    class="miner-list-item items-center"
                  >
                    <Images
                      class="miner-list-item-img"
                      :src="imgUrl.avatarDefault"
                    />
                    <div class="miner-list-item-nick">
                      <img
                        class="miner-list-item-nick-bg"
                        src="/image/mining/wkdrbg-icon.svg"
                      />
                      <div class="miner-list-item-nick-text">
                        {{ t("mvp.mining.text8") }}
                      </div>
                    </div>
                    <div class="miner-list-item-bdc">
                      {{ t("mvp.mining.text8") }}
                    </div>
                  </div>
                  <div v-else class="miner-list-item items-center">
                    <Images
                      class="miner-list-item-img"
                      :src="item.avatar || imgUrl.avatarDefault"
                      isHttp
                    />

                    <div class="miner-list-item-nick">
                      <img
                        class="miner-list-item-nick-bg"
                        src="/image/mining/wkdrbg-icon.svg"
                      />
                      <div class="miner-list-item-nick-text">
                        {{
                          item.nickname ? item.nickname.substring(0, 11) : "--"
                        }}
                        <span style="margin-left: -4px">
                          {{
                            item.nickname && item.nickname.length > 11
                              ? "..."
                              : ""
                          }}
                        </span>
                      </div>
                    </div>
                    <div class="miner-list-item-bdc">
                      {{ item.cumulativeAcquireAmount }} BDC
                    </div>
                  </div>
                </template>
              </div>
            </div>
            <!-- banner 位置  v-if="pageData.bannerList.length > 0" -->
            <div v-if="false" class="banner">
              <van-swipe :autoplay="3000" lazy-render indicator-color="#007BFF">
                <van-swipe-item
                  v-for="image in pageData.bannerList"
                  :key="image.id"
                  @click="jumpPage(image, true)"
                >
                  <Images class="banner-img" :src="image.pic_path" isHttp />
                </van-swipe-item>
              </van-swipe>
            </div>
          </div>
        </van-pull-refresh>
      </ClientOnly>
    </div>
    <InviteFriendsTaskPopup
      v-if="isTaskPopup"
      v-model:show="isTaskPopup"
      v-model:forcedDisplay="forcedDisplay"
      :inviterInfo="inviterInfo"
    ></InviteFriendsTaskPopup>
  </div>
</template>
<script setup name="mining">
import {
  navigateI18nTo,
  isiOS,
  getOssFileUrl,
  jumpLocalH5PageRoute,
  getImagePrefix,
  debounce,
  throttle,
  toThousands,
  switchTabBar,
} from "@/utils";
import InviteFriendsTaskPopup from "../../components/invite-friends/invite-friends-task-popup.vue";
import { JUMPAPPS } from "~/config";
import MiningBox from "~/components/mvp/mining.vue";
import { useGlobalStore } from "~~/store/global";
import { useUserStore } from "~~/store/modules/user";
import {
  getBoxList,
  getBannerList,
  getBoxmineInfo,
  openBox,
  openBoxAll,
  getMinerExpert,
  getRecentActivity,
  getCumulativeAcquireInfo,
} from "../../../api/bdc";
import { useWindowSize, useRect, usePageVisibility } from "@vant/use";
import { defineAsyncComponent } from "vue";
import { onUnmounted } from "vue";
import { useEventBus } from "@vueuse/core";
import { usePageCacheStore } from "../store/modules/pageCache";
import { useLotteryV3Store } from "~~/store/modules/lottery-v3";
import { registerInviteNewUserBonus } from "@/api/inviteFriends";

import Broadcast from "@/components/info-scroll/index.vue";
import MiningCell from "@/components/info-scroll/mining.vue";

const CountTo = defineAsyncComponent(() =>
  import("~/components/countTo/index.vue")
);

// definePageMeta({
//   keepalive: true,
// });

const globalStore = useGlobalStore();
// 如果没有登录-直接跳转登录页面
if (!globalStore.$state.token && process.client) {
  bridge.onAppLogin();
}
const lotteryV3Store = useLotteryV3Store();
const pageCache = usePageCacheStore();
const { t } = useI18n();
// const route = useRoute();
// console.log("mining页面参数:", route.query);

// firebase埋点
const firebase = useInitFirebase(); // 初始化firebase
const tabBarBadgeEmit = useEventBus("tab-bar-badge-on");
const imgUrl = getOssFileUrl({
  avatarDefault: "/image/avatar-default.png",
  bdc: "/image/mvp/bdc.png",
  lottery: "/lottie/lottery/lottery.json",
  // tooltipBg: "/image/mvp/tooltip-bg1.png",
});

const userState = useUserStore();
// 获取窗口宽度和高度
const { width, height } = process.client
  ? useWindowSize()
  : { width: ref(320), height: ref(667) };

// 用户等级
let userLevel = computed(() => {
  return getOssFileUrl({
    level: `/image/mining/V${
      (userState.$state && userState.$state.vipNum) || "0"
    }.png`,
  }).level;
});

const isShowXing = computed(() => {
  return (
    userLevel.value.includes("V4") ||
    userLevel.value.includes("V5") ||
    userLevel.value.includes("V6")
  );
});

// 宝箱宽度
const box_w = (48 / 390) * width.value;
// 宝箱位置 390 代表 iphone14 的宽度
const boxPosition = [
  {
    sort: 1,
    x: `${((95 + box_w / 2) / 390) * 100}%`,
    y: (102 / 390) * width.value,
  },
  {
    sort: 2,
    x: `${((92 + box_w / 2) / 390) * 100}%`,
    y: (26 / 390) * width.value,
  },
  {
    sort: 3,
    x: `${((177 + box_w / 2) / 390) * 100}%`,
    y: (70 / 390) * width.value,
  },
  {
    sort: 4,
    x: `${((275 + box_w / 3) / 390) * 100}%`,
    y: (100 / 390) * width.value,
  },

  {
    sort: 5,
    x: `${((12 + box_w / 3) / 390) * 100}%`,
    y: (82 / 390) * width.value,
  },
  {
    sort: 6,
    x: `${((280 + box_w / 3) / 390) * 100}%`,
    y: (20 / 390) * width.value,
  },
  {
    sort: 7,
    x: `${((8 + box_w / 3) / 390) * 100}%`,
    y: (5 / 390) * width.value,
  },
  {
    sort: 8,
    x: `${((186 + box_w / 3) / 390) * 100}%`,
    y: (0 / 390) * width.value,
  },
  {
    sort: 9,
    x: `${((190 + box_w / 3) / 390) * 100}%`,
    y: (135 / 390) * width.value,
  },
  {
    sort: 10,
    x: `${((30 + box_w / 3) / 390) * 100}%`,
    y: (147 / 390) * width.value,
  },
];
// 宝箱枚举
const boxEnum = {
  1: {
    w: `${box_w}px` || "48px",
    h: `${box_w}px` || "48px",
    img: "/image/mvp/box1.png",
    imgOpen: "/image/mvp/box1-open.png",
  },
  2: {
    w: `${box_w}px` || "48px",
    h: `${box_w}px` || "48px",
    img: "/image/mvp/box2.png",
    imgOpen: "/image/mvp/box2-open.png",
  },
  3: {
    w: `${box_w}px` || "48px",
    h: `${box_w}px` || "48px",
    img: "/image/mvp/box3.png",
    imgOpen: "/image/mvp/box3-open.png",
  },
  4: {
    w: `${box_w}px` || "48px",
    h: `${box_w}px` || "48px",
    img: "/image/mvp/box4.png",
    imgOpen: "/image/mvp/box4-open.png",
  },
};

const menus = ref([
  {
    title: t("mvp.mining.text4"),
    path: "integralShop",
  },
  {
    title: t("mvp.mining.text5"),
    path: "taskCenter",
  },
  {
    title: t("mvp.assetDetails.text8"),
    path: "ranking",
  },
  {
    title: t("mvp.mining.text2"),
    path: "desc",
  },
]);

// 页面属性
const pageData = reactive({
  whiteTheme: true,
  loading: false,
  loadingAll: false,
  navBarHeight: 0,
  bannerList: [],
  pageNum: 1,
  total: 0,
  userList: [],
  boxList: [],
  mineInfo: {
    cumulativeAcquireAmount: 0, // bdc 累计数量
    // cumulativeAcquireValue: 0, // 美元价值
  },
  cumulativeAcquireAmount: 0, // 增量以后：bdc 累计数量
  // cumulativeAcquireValue: 0, // 增量以后：美元价值
  paused: false, // 是否暂停动画
  // 跑马灯
  miningNums: 0,
  broadcasts: [],
  autoplay: 2000,
  isClicktooltip: 0,
});

// 宝箱视图
const boxview = ref();
const boxviewRect = computed(() => {
  return useRect(boxview);
});

// 收钱对象
const bdcRef = ref();
const bdcRect = computed(() => {
  // console.log("---------------bdcRef----");
  return useRect(bdcRef);
});

// 接收滚动事件，传递给导航组件
const scrollEl = ref();

// 下拉状态变更
const refreshChange = ({ status, distance }) => {
  // console.log("--status--", status, "--distance--", distance);
  if (status !== "normal" || distance > 0) {
    isPausedAnimation(true);
  } else {
    isPausedAnimation(false);
  }
};
// 开始/暂停动画
const isPausedAnimation = (isPaused) => {
  if (isPaused) {
    pageData.paused = true;
  } else {
    pageData.paused = false;
  }
};

// 是否显示一键开箱
let isShowOpenAllBtn = ref(false);
// 是否正在进行一键开箱
let openAllIng = false;

// 获取 banner 列表
const getBannerListRequest = async () => {
  const res = await getBannerList({ type: 1 });
  // console.log("--banner列表--", res);
  if (res) {
    let arr = [];
    res.indexBanner.forEach((element) => {
      if (element.type == 27) {
        arr.push(element);
      }
    });
    pageData.bannerList = arr;
  }
};
// 获取宝箱列表
const getBoxListRequest = async () => {
  const res = await getBoxList({
    pageNum: pageData.pageNum,
    pageSize: 10,
  });
  // console.log("--宝箱列表--", res);
  if (res) {
    // 1. 获取宝箱总数量,并修改 tabbar 上的标记
    pageData.total = res.total || 0;
    tabBarBadgeEmit.emit(res.total);
    // 2. 加工数据
    if (res.records.length > 0) {
      pageData.boxList = res.records.map((e, index) => {
        const position = boxPosition[index];
        const boxStyle = boxEnum[e.level];
        return {
          id: e.id,
          level: e.level,
          ...position,
          ...boxStyle,
          sendAmount: e.sendAmount,
          isOpen: false,
          taskType: e.taskType,
        };
      });
    } else {
      pageData.boxList = [];
    }
    // 时候展示一键开箱
    isShowOpenAllBtn.value = pageData.boxList.length > 2;
  }
};
// 获取挖矿信息
const getBoxmineInfoRequest = async () => {
  const res = await getBoxmineInfo();
  // console.log("--获取挖矿信息--", res);
  // res.cumulativeAcquireAmount = 8888888888.55;
  if (res) {
    res.cumulativeAcquireAmount = Number(res.cumulativeAcquireAmount);
    pageData.cumulativeAcquireAmount = res.cumulativeAcquireAmount;
    // res.cumulativeAcquireAmount =  555555555.55 || Number(res.cumulativeAcquireAmount);
    // pageData.cumulativeAcquireAmount = 555555555.55 ||res.cumulativeAcquireAmount;
    pageData.mineInfo = res;
  }
};
// 获取-挖矿达人
const getMinerExpertRequest = async () => {
  const res = await getMinerExpert();
  pageData.userList = [];
  // console.log("--挖矿达人--", res);
  if (res) {
    if (res.length < 3) {
      for (let index = 0; index < 3; index++) {
        const element = res[index];
        if (element) {
          if (
            !element.avatar ||
            element.avatar == "https://asset.onetrader.online/"
          ) {
            element.avatar = imgUrl.avatarDefault;
          }
          pageData.userList.push(element);
        } else if (pageData.userList.length < 3) {
          pageData.userList.push("occupy");
        }
      }
    } else {
      pageData.userList = res.map((e) => {
        if (!e.avatar || e.avatar == "https://asset.onetrader.online/") {
          e.avatar = imgUrl.avatarDefault;
        }
        return e;
      });
    }
  } else {
    pageData.userList = ["occupy", "occupy", "occupy"];
  }
};
// 一键开箱
const bdcCollectAll = debounce(() => {
  openAllIng = true;
  if (!isShowOpenAllBtn.value) return;
  // 1. 防止重复点击
  isShowOpenAllBtn.value = false;
  // 2. 做动画
  pageData.boxList.forEach((e) => {
    e.manual = true;
  });
}, 1400);

// 单独开箱
const openBoxRequest = async (val) => {
  // const res = {
  //   acquireAmount: 1520,
  //   acquireValue: 100,
  // };

  const res = await openBox({
    id: val.id,
  });

  if (res) {
    // 1. 计算结束值，开始动画
    pageData.cumulativeAcquireAmount += Number(res.acquireAmount);
    // 2. 重新赋值开始值，以便后续累加

    setTimeout(() => {
      pageData.mineInfo.cumulativeAcquireAmount =
        pageData.cumulativeAcquireAmount;
    }, 1000);
    // 3. tabbar 上的标记 -1
    pageData.total -= 1;
    if (pageData.total < 0) pageData.total = 0;
    tabBarBadgeEmit.emit(pageData.total);
  }
};
// 批量开箱
const openBoxAllRequest = throttle(async (idList) => {
  // console.log("--进来了--", user_sid.value);
  // 0. 暂停动画
  isPausedAnimation(true);

  // const res = {
  //   successList: [
  //     {
  //       acquireAmount: 150,
  //       acquireValue: 0.15,
  //     },
  //   ],
  //   failedList: [
  //     {
  //       id: 1,
  //     },
  //     {
  //       id: 2,
  //     },
  //   ],
  // };
  // 2. 请求
  const res = await openBoxAll({
    idList,
  });

  if (res) {
    // 成功的宝箱
    if (res.successList && res.successList.length > 0) {
      // 1. 开始滚动动画
      pageData.cumulativeAcquireAmount += Number(res.totalAcquireAmount);
      // pageData.cumulativeAcquireValue +=Number(res.totalAcquireValue);
      // 2. 重新赋值开始值，以便后续累加
      pageData.total -= res.successList.length;
      if (pageData.total < 0) pageData.total = 0;
      setTimeout(() => {
        pageData.mineInfo.cumulativeAcquireAmount =
          pageData.cumulativeAcquireAmount;
        // pageData.mineInfo.cumulativeAcquireValue =
        // pageData.cumulativeAcquireValue;
      }, 1000);
    }
  }
  // 一键开箱结束，恢复状态
  openAllIng = false;
}, 1500);
// 宝箱-开箱
let openIds = []; // 记录要-单独-开箱的 id
const openBoxCall = async (val) => {
  if (!val) return;
  // 1. 删除移动完成的点
  setTimeout(() => {
    pageData.boxList = pageData.boxList.filter((e) => {
      return e.sort != val.sort;
    });
    if (pageData.boxList.length <= 0) {
      getBoxListRequest().then(() => {
        if (pageData.boxList.length > 2 && !isShowOpenAllBtn.value) {
          isShowOpenAllBtn.value = true;
        }
      });
    } else {
      if (pageData.boxList.length <= 2) {
        isShowOpenAllBtn.value = false;
      }
    }
    // console.timeEnd("1---1");
    // 1.1 开始动画
    isPausedAnimation(false);
  }, 1450);

  // 2. 发起请求
  if (openAllIng) {
    // 2.1 获取 ids
    const boxIds = pageData.boxList
      .filter((e) => {
        return !openIds.includes(e.id);
      })
      .map((e) => e.id);

    // 这个函数做了节流，能保证值执行一次
    openBoxAllRequest(boxIds);
  } else {
    // 2.2 添加已开箱的 id
    openIds.push(val.id);
    openBoxRequest(val);
  }
};

// 获取-查询挖矿动态
const getRecentActivityRequest = async () => {
  const res = await getRecentActivity();

  // console.log("--查询挖矿动态--", res);
  if (res) {
    const icons = ["👑", "💪", "🚀", "💰", "💎", "🎁", "🔥", "✨", "👍", "🔮"];
    const min = 0;
    const max = 9;
    pageData.broadcasts = res.map((e, idx) => {
      const randomInt = Math.floor(Math.random() * (max - min + 1)) + min;
      const randomInt1 = Math.floor(Math.random() * (max - min + 1)) + min;
      const d2qy = Math.floor(Math.random() * (max - min + 1)) + min;
      let text = icons[randomInt];
      if (randomInt1 != randomInt && d2qy % 2 === 0) {
        text += `  ${icons[randomInt1]}`;
      }

      // 处理头像问题
      let avatar = e.avatar;
      if (!avatar || avatar == "https://asset.onetrader.online/") {
        avatar = imgUrl.avatarDefault;
      } else {
        avatar = getImagePrefix() + e.avatar;
      }
      return {
        id: e.id || idx,
        avatar,
        acquireAmount: e.changeAmount,
        nickname: e.nickname,
        tradeTypeShow: e.tradeTypeShow || "",
        miningtext: text,
        showPopover: false,
      };
    });
  }
};

// 页面每次进入-需要刷新的请求
const onRefreshRequest = () => {
  try {
    // 1. 重新获取宝箱，防止宝箱过期还在显示
    pageData.loadingAll = false;
    pageData.pageNum = 1;
    const a = getBoxListRequest().then(() => {
      // 1.2 挖矿信息数据(后端要求，在上一个请求执行完成以后再请求这个)
      getBoxmineInfoRequest();
    });
    // 2. 累计人数
    const b = getCumulativeAcquireInfo().then((res) => {
      if (res) {
        // console.log("--累计人数--", res);
        pageData.miningNums = res.cumulativeAcquireCount;
      }
    });

    Promise.all([a, b]).finally(() => {
      pageData.loading = false;
      nextTick(() => {
        pageData.loadingAll = true;
      });
    });
  } catch (error) {
    pageData.loading = false;
  }
};

// 不需要频繁的请求
const onLoadRequest = () => {
  // 1. 挖矿达人
  getMinerExpertRequest();
  // 2. 获取跑马灯数据
  getRecentActivityRequest();
  // 3. 获取 banner
  // getBannerListRequest();
};

// 页面可见状态(当前页面是否进入后台) https://vant-contrib.gitee.io/vant/#/zh-CN/use-page-visibility
const pageVisibility = usePageVisibility();
watch(pageVisibility, (value) => {
  // console.log("从后台进入前台: 刷新数据 ", value);
  if (value == "visible") onRefreshRequest();
});

// 下拉刷新
const onRefresh = () => {
  onRefreshRequest();
  onLoadRequest();
};

let terval = null;
onMounted(() => {
  // console.log("--onMounted--");
  // 1. 埋点访问
  firebase?.logEvent("BDC_H5_Mining_PUV", {
    time: Date.now(),
  });
  // 2. 请求接口
  onLoadRequest();
  onRefreshRequest();
  // 3. 每五分钟更新一次;
  terval = setInterval(() => {
    // 3.1 挖矿达人
    getMinerExpertRequest();
    // 3.2 累计人数
    getCumulativeAcquireInfo().then((res) => {
      if (res) {
        // console.log("--累计人数--", res);
        pageData.miningNums = res.cumulativeAcquireCount;
      }
    });
  }, 1000 * 60 * 5);
  // 4. 邀请好友,任务弹窗
  taskPopupLoad();
});

onUnmounted(() => {
  terval && clearInterval(terval);
});
onActivated(() => {
  console.log("--onActivated--");
  // 1. 刷新数据
  onRefreshRequest();
});
onDeactivated(() => {
  console.log("--onDeactivated--");
  terval && clearInterval(terval);
});

// 页面跳转
const jumpPage = async (type, isApp = false) => {
  if (isApp) {
    if (type === "taskCenter") {
      firebase?.logEvent("BDC_H5_Mining_TaskCenter_Click"); // 埋点访问
      bridge.jumpAppRoute(JUMPAPPS()[type]);
    } else if (type === "integralShop") {
      firebase?.logEvent("BDC_H5_Mining_IntegralShop_Click"); // 埋点访问
      bridge.jumpAppRoute(JUMPAPPS()[type]);
    } else if (type.ios_url || type.android_url) {
      if (
        type.ios_url.startsWith("native://") ||
        type.android_url.startsWith("https://btcdana.com/")
      ) {
        bridge.jumpAppRoute(isiOS.value ? type.ios_url : type.android_url);
      } else {
        let thirdUrl = isiOS.value ? type.ios_url : type.android_url;
        // 如果是跳转自己的 h5 页面,则走导航跳转
        if (thirdUrl.startsWith(location.origin + "/fx/")) {
          // 方案一： 路由跳转
          jumpLocalH5PageRoute(thirdUrl);
          // 方案二： 链接加参数
          // jumpLocalH5PageUrl(thirdUrl)
        } else if (thirdUrl.includes("webview=1")) {
          navigateI18nTo({
            path: "/webview",
            query: { src: thirdUrl, title: type.name },
          });
        } else {
          await navigateTo(thirdUrl, {
            external: true,
          });
        }
      }
    }
  } else if (type === "assetDetails") {
    firebase?.logEvent("BDC_H5_Mining_AssetDetails_Click"); // 埋点访问
    await navigateI18nTo({ path: "/mvp/assetDetails" });
  } else if (type === "coin") {
    firebase?.logEvent("BDC_H5_Mining_Coin_Click"); // 埋点访问
    await navigateI18nTo({ path: "/mvp/coin/coin" });
  } else if (type === "desc") {
    pageCache.removeData("desc-activity-refIdx");
    firebase?.logEvent("BDC_H5_Mining_Desc_Click"); // 埋点访问
    await navigateI18nTo({ path: "/mvp/mining/desc" });
  } else if (type === "exchangeCoupon") {
    // firebase?.logEvent("BDC_H5_Mining_ExchangeCoupon_Click"); // 埋点访问
    // await navigateI18nTo({ path: "/mvp/exchangeCoupon" });
  } else if (type === "lottery") {
    firebase?.logEvent("BDC_H5_Mining_Lottery_Click"); // 埋点访问
    await navigateI18nTo({ path: "/lottery" });
  } else if (type === "airdrop") {
    firebase?.logEvent("BDC_H5_Mining_Airdrop_Click"); // 埋点访问
    await navigateI18nTo({ path: "/airdrop" });
  } else if (type === "arousaluser") {
    firebase?.logEvent("BDC_H5_Mining_Arousal_Click");
    await navigateI18nTo({ path: "/arousal-user" });
  } else if (type === "pledge") {
    firebase?.logEvent("BDC_H5_Mining_Pledge_Click");
    await navigateI18nTo({ path: "/pledge" });
  } else if (type === "ranking") {
    firebase?.logEvent("BDC_H5_Mining_Pledge_Click");
    await navigateI18nTo({ path: "/mvp/ranking" });
  } else if (type === "assets") {
    // switchTabBar("mvp-assetDetails__");
    firebase?.logEvent("BDC_H5_Mining_MingDetail_Click");
    await navigateI18nTo({ path: "/mvp/mining/incomeStatement" });
  } else if (type === "inviteFriendsMonery") {
    firebase?.logEvent("BDC_H5_Mining_inviteFriendsMonery_Click");
    await navigateI18nTo({ path: "/lottery-v3/invite-friends" });
  }
};

/**
 * 邀请好友弹窗:
 * 1. 点击入口按钮直接展示
 * 2. 今日完成所有任务以后也不会展示
 * 3. 本地缓存判断
 * */
const isTaskPopup = ref(false);
const forcedDisplay = ref(false); // 强制展示
const inviterInfo = ref(); // 邀请人信息
// const inviterInfo = ref({
//   sid: "10000150446",
//   nickname: "zhj1214",
//   avatar:
//     "/upload/picture/feed/1694658686167-ba36bb8d5c104e60819f12245f40ffe3.png",
//   vipLevel: 4,
//   regPrize: "2000",
//   regPrizeStatus: 0, // 被邀请人奖励状态 0:进行中 1:已完成 2:风控拒绝 3:待发放
//   bindEmailStatus: 1, // 被邀请人绑定邮箱状态 0:进行中 1:已完成 2:风控拒绝 3:待发放
// }); // 邀请人信息

// 查询邀请人信息 2024.11.20 删除
const taskPopupLoad = () => {
  // registerInviteNewUserBonus().then((res) => {
  //   console.log("查询邀请人信息:", res);
  //   if (res && res.inviterInfo) {
  //     inviterInfo.value = res.inviterInfo;
  //     isTaskPopup.value = true;
  //   }
  // });
};
// 改变弹窗显示状态
const isTaskPopupChange = (val) => {
  isTaskPopup.value = val;
  forcedDisplay.value = val;
};
</script>
<style lang="scss" scoped>
.mining {
  /* 禁止在整个页面范围内的溢出回弹效果 */
  overscroll-behavior-y: none !important;
  // height: calc(100vh - 50 * 2px);
  overflow-y: scroll;
  will-change: scroll-position;
  overflow-x: hidden;
  background: #fff;
  background-repeat: no-repeat;
  position: relative;

  .content {
    position: relative;
    &-color {
      position: absolute;
      top: 0;
      left: 0;
      width: 100vw;
      height: 40vh;
      background-color: #0079fb;
    }
    &-bg {
      position: absolute;
      left: 0px;
    }

    &-zindex {
      position: relative;
      z-index: 1;
    }
  }
}
.header {
  position: relative;
  &-top {
    display: inline-flex;
    position: relative;
    margin-left: 15 * 2px;
    margin-top: 20 * 2px;

    &-bdc {
      min-width: 225 * 2px;
      position: relative;
      top: -2px;
      left: 0;
      z-index: 5;
      padding: 1.5 * 2px 0;
      padding-left: 15 * 2px;

      &-jt {
        margin-right: 15 * 2px;
        width: 10 * 2px;
        height: 10 * 2px;
      }

      &-icon {
        margin-right: 8 * 2px;
        width: 32 * 2px;
        height: 32 * 2px;
        padding: 2 * 2px 0;
      }
      &-text {
        width: 80 * 2px;
        line-height: 12 * 2px;
        color: #007bff;
        font-size: 11 * 2px;
        font-weight: 590;
        margin-right: 8 * 2px;
      }
      &-value {
        color: #007bff;
        font-size: 17 * 2px;
        font-weight: 700;
        margin-right: 8 * 2px;
      }
    }
    &-bg {
      &-left {
        position: absolute;
        top: 0;
        left: 0;
        height: 100%;
        object-fit: cover;
      }
      &-right {
        position: absolute;
        top: 0;
        right: 0;
        height: 100%;
        object-fit: cover;
      }
    }
  }
}
.boxview {
  @keyframes shanshuo {
    0% {
      opacity: 1;
    }

    100% {
      opacity: 0;
    }

    0% {
      opacity: 1;
    }
  }
  position: relative;
  top: 30 * 2px;
  min-height: 209 * 2px;
  width: 100vw;
  &-item {
    position: absolute;
    flex-direction: column;
    justify-content: center;
    min-width: 72 * 2px;
  }
  &-xingxing {
    width: 24 * 2px;
    height: 24 * 2px;
  }
  &-xing1 {
    position: absolute;
    z-index: 99;
    top: 686px;
    left: 288px;
    animation: shanshuo 0.95s infinite ease;
    animation-direction: alternate;
  }
  &-xing2 {
    position: absolute;
    top: 796px;
    left: 483px;
    animation: shanshuo 0.8s infinite ease;
    animation-direction: alternate;
  }
  &-xing3 {
    position: absolute;
    top: 815px;
    left: 595px;
    animation: shanshuo 0.6s infinite ease;
    animation-direction: alternate;
  }
}

.openall {
  position: relative;
  top: 38px;
  // left: 50px;
  justify-content: center;
  width: 100vw;
  height: 50 * 2px;
  border-radius: 100px;
  padding: 2 * 2px;
  &-bg {
    padding: 2 * 2px;
    border-radius: 100px;
    background: linear-gradient(
      225deg,
      #149aff 0.1%,
      #007bff 50.1%,
      #0051e7 100.1%
    );
    background-repeat: no-repeat;
    background-size: 100%;
    border: 4px solid #92c3ff;
  }
  &-text {
    padding: 4 * 2px 16 * 2px;
    border-radius: 100px;
    font-size: 15 * 2px;
    color: #fff;
    font-weight: 590;
    background: linear-gradient(
      228deg,
      #68beff -5.05%,
      #3292f9 50.11%,
      #0c5df3 105.28%
    );
    background-repeat: no-repeat;
    background-size: 100%;
  }
}

.unclaimed {
  position: absolute;
  z-index: 99;
  top: 658px;
  right: 85px;
  width: 160 * 2px;
  border-radius: 8 * 2px;
  border: 3px solid #fff;
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(4px);
  padding: 6 * 2px 10 * 2px;
  word-break: break-word;
  &-text {
    color: #5b6272;
    font-size: 11 * 2px;
  }
  &-icon {
    position: absolute;
    left: -13px;
    top: 50%;
    transform: translate(0, -50%);
  }
}
.user {
  position: relative;
  top: 25 * 2px;
  left: 165px;
  width: 150 * 2px;
  height: 205 * 2px; // 用于撑起高度
  &-logo {
    width: 150 * 2px;
    height: 150 * 2px;
  }
}

.broadcastview {
  position: relative;
  margin-bottom: 15 * 2px;
}

@supports (backdrop-filter: blur(30px)) or (-webkit-backdrop-filter: blur(30px)) {
  .mantle-filter {
    background: linear-gradient(
      180deg,
      rgba(255, 255, 255, 0.7) 0%,
      rgba(255, 255, 255, 0.8) 54.9%
    ) !important;
    backdrop-filter: blur(30px);
    -webkit-backdrop-filter: blur(30px);
  }
}

.mantle {
  position: relative;
  z-index: 99;
  background-color: #fff;
  border: 2px solid rgba(255, 255, 255, 0.4);
  padding: 15 * 2px;
  border-top-right-radius: 12 * 2px;
  border-top-left-radius: 12 * 2px;
  .operate {
    margin-top: 10 * 2px;
    margin-bottom: 30 * 2px;
    &-item {
      flex-direction: column;
      justify-content: center;
      width: 25%;
    }
  }
  .miner {
    padding: 20 * 2px 12 * 2px;
    border-radius: 12 * 2px;
    background: linear-gradient(180deg, #f4f9ff 0%, #fff 100%);
    &-top {
      flex-direction: column;
      justify-content: center;
      &-title {
        text-align: center;
        color: #141924;
        font-size: 15 * 2px;
        font-weight: 590;
        margin-bottom: 20 * 2px;
      }
      &-num {
        margin-bottom: 20 * 2px;
        display: inline-flex;
        align-items: center;
        color: #fff;
        font-size: 18 * 2px;
        font-weight: 750;
        background: linear-gradient(90deg, #007bff 53.61%, #00b2ff 100.19%);
        padding: 4 * 2px 19 * 2px;
        border-radius: 100px;
        &-text {
          font-style: italic;
          margin-left: 10 * 2px;
          color: #fff;
          font-size: 11 * 2px;
          font-weight: 590;
        }
      }
    }
    &-list {
      justify-content: space-between;
      &-item {
        padding: 15 * 2px 10 * 2px;
        flex-direction: column;
        justify-content: center;
        border-radius: 12 * 2px;
        border: 2px solid rgba(115, 119, 128, 0.15);
        &-img {
          width: 48 * 2px;
          height: 48 * 2px;
          border-radius: 100px;
          border: 3px solid rgba(0, 0, 0, 0.1);
          overflow: hidden;
        }
        &-nick {
          position: relative;
          top: -6px;
          min-width: 85 * 2px;
          margin-bottom: 6px;
          &-text {
            position: relative;
            z-index: 1;
            padding: 4 * 2px 0;
            color: #002853;
            font-size: 11 * 2px;
            font-weight: 590;
            text-align: center;
          }
          &-bg {
            position: absolute;
            top: 0;
            left: 0;

            min-width: 85 * 2px;
            min-height: 20px;
          }
        }
        &-bdc {
          color: #1b7aff;
          font-size: 11 * 2px;
          font-weight: 750;
        }
      }
    }
  }
}
.inviteFriends {
  @keyframes waveYy {
    0% {
      transform: translateY(-4.2px);
    }
    50% {
      transform: translateY(4.2px);
    }
    100% {
      transform: translateY(-4.2px);
    }
  }

  justify-content: center;
  flex-direction: column;
  position: absolute;
  z-index: 9;
  width: 100vw;
  margin-top: 10%;
  transform: translate(-50%, -50%);
  animation: waveYy 4.5s infinite ease-in-out;
  &-img {
    width: 110 * 2px;
    height: 110 * 2px;
  }
  &-text {
    width: 50%;
    margin-top: -12 * 2px;
    color: #007bff;
    text-align: center;
    font-size: 10 * 2px;
    font-weight: 400;
    background: linear-gradient(
      90deg,
      rgba(255, 255, 255, 0) 0%,
      rgba(255, 255, 255, 0.4) 50.2%,
      rgba(255, 255, 255, 0) 100%
    );
    backdrop-filter: blur(4 * 2px);
    padding: 4 * 2px 8 * 2px;
  }
}
.xrfl {
  position: absolute;
  top: 70 * 2px;
  right: -1px;
  z-index: 9;
  display: inline-flex;
  padding: 4 * 2px 15 * 2px 4 * 2px 10 * 2px;
  border-radius: 100px 0 0 100px;
  border: 1px solid rgba(255, 255, 255, 0.4);
  background: rgba(255, 255, 255, 0.4);
  backdrop-filter: blur(20px);
  &-img {
    width: 16 * 2px;
    height: 16 * 2px;
    margin-right: 4 * 2px;
  }
  &-text {
    font-size: 12 * 2px;
    color: #002853;
    font-weight: 590;
  }
}
</style>
<style lang="scss">
.banner {
  .van-swipe__indicator {
    left: 25% !important;
  }
}
:root:root {
  --van-pull-refresh-head-text-color: #fff;
}
.pull-refresh {
  overflow: initial;
  .van-pull-refresh__head {
    z-index: 99;
  }
  .van-loading__text {
    z-index: 9999999;
    color: #fff;
  }
}
</style>
